package epoverty;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;

public class Trips extends JPanel
{
   private final int width = super.getWidth();
   private final int height = super.getHeight();
   private BufferedImage leftArrow = Util.resizeImage(ImageIO.read(new File("leftArrows.jpg")), 70, 150);
   private BufferedImage rightArrow = Util.resizeImage(ImageIO.read(new File("rightArrows.jpg")), 70, 150);
   private BufferedImage defaultImage = Util.resizeImage(ImageIO.read(new File("NoImage.jpg")), 150, 130);
   private JPanel mainPanel;
   private Trips.myTable tripsTable, fundraisers;
   private JTextField searchTF, tripNameTF, costTF, defaultRaiseGoalTF,
      cutoffDateTF, departDateTF, returnDateTF;
   private JTextArea descriptionTA;
   private static JComboBox tripsList;
   private JLabel photo1, photo2, photo3, photo4, photo5, photo6, leftScroll, rightScroll, tripName, cost,
      defaultRaiseGoal, cutoffDate, departDate, returnDate;
   private JButton editBTN, cutoffBTN, departBTN, returnBTN;
   private JRadioButton currentRB, pastRB;
   private static ArrayList<Object> possibleTrips, formattedTrips;
   private static ArrayList<BufferedImage> photosList;
   private int tripID;
   private static int photoStartPosition = 0;
   private String tripSelected;
   private final JPanel tripNameCardPanel, cutoffCardPanel, departCardPanel, returnCardPanel,
      costCardPanel, defaultRaiseCardPanel;
   private boolean edit = false;

   Trips(JTabbedPane tabs) throws IOException, ClassNotFoundException, SQLException, ParseException
   {
      //******************************************Set up UI
      UIManager.put("Table.background", Color.DARK_GRAY);
      UIManager.put("Table.foreground", Color.WHITE);
      UIManager.put("Table.font", new Font("SansSerif", Font.BOLD, 14));
      UIManager.put("Table.selectionBackground", Color.GREEN);
      UIManager.put("Table.selectionForeground", Color.BLACK);
      UIManager.put("Table.gridColor", Color.BLACK);
      UIManager.put("TableHeader.background", Color.GRAY);
      UIManager.put("TableHeader.foreground", Color.GREEN);
      UIManager.put("TableHeader.font", new Font("SansSerif", Font.BOLD, 16));
      UIManager.put("OptionPane.background", Color.DARK_GRAY);
      UIManager.put("OptionPane.messageForeground", Color.WHITE);
      UIManager.put("OptionPane.okButtonText", "Login");
      UIManager.put("Panel.background", Color.DARK_GRAY);
      UIManager.put("Label.foreground", Color.WHITE);
      UIManager.put("Label.foreground", Color.LIGHT_GRAY);
      UIManager.put("Label.font", new Font("Serif", Font.BOLD, 18));
      UIManager.put("TextField.font", new Font("Serif", Font.PLAIN, 18));
      UIManager.put("TextField.foreground", Color.BLACK);
      UIManager.put("Button.background", EPovertyMain.darkest);
      UIManager.put("Button.foreground", Color.WHITE);
      UIManager.put("RadioButton.background", Color.DARK_GRAY);
      UIManager.put("RadioButton.foreground", Color.WHITE);
      UIManager.put("TextField.background", new Color(100, 100, 100));
      UIManager.put("TextField.foreground", Color.WHITE);
      UIManager.put("TextField.caretForegroud", Color.WHITE);
      UIManager.put("PasswordField.background", new Color(100, 100, 100));
      UIManager.put("PasswordField.foreground", Color.WHITE);
      UIManager.put("CheckBox.background", Color.DARK_GRAY);
      UIManager.put("CheckBox.foreground", Color.WHITE);

      GridBagConstraints gBC = new GridBagConstraints();
      Border compoundProgress;
      Border raisedbevel = BorderFactory.createRaisedBevelBorder();
      Border loweredbevel = BorderFactory.createLoweredBevelBorder();
      Border border = BorderFactory.createLineBorder(Color.GREEN);
      compoundProgress = BorderFactory.createCompoundBorder(raisedbevel, loweredbevel);
      Border insideBorders = BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GREEN), compoundProgress);
     
      // *****************************************MAIN PANEL
      mainPanel = new JPanel();
      mainPanel.setLayout(new MigLayout("wrap 1, fill, insets 0"));
      Dimension mainFundraiser = new Dimension(width, height - 15);
      mainPanel.setBorder(border);
      //mainPanel.setPreferredSize(mainFundraiser);
      mainPanel.setBackground(Color.DARK_GRAY);
      final JFrame f = new JFrame();
      f.getContentPane().add(mainPanel);
      f.pack();

      // *****************************************CREATE FIRST PANEL (NAV BAR) IN TAB
      JPanel navPanel = new JPanel();
      //navPanel.setBorder(insideBorders);
      navPanel.setLayout(new MigLayout(
         "insets 3",
         "[grow][][center][][grow][]",
         "[]0[]"));

      // *****************************************CREATE SECOND PANEL (TABLE) IN TAB
      BackgroundPanel topTripsTab = new BackgroundPanel(null, BackgroundPanel.ACTUAL, 1.0f, 0.5f);
      topTripsTab.setBorder(insideBorders);
      topTripsTab.setLayout(new GridLayout(0, 1, 1, 1));
      Dimension topTrips = new Dimension(width, 350);
      //topFundraisersTab.setPreferredSize(topFundraiser);
      GradientPaint paintTopTrips = new GradientPaint(0, 0, Color.BLACK, 100, 100, Color.DARK_GRAY);
      topTripsTab.setPaint(paintTopTrips);

      // *****************************************CREATE THIRD (PICTURES) PANEL IN TAB
      BackgroundPanel middleTripsTab = new BackgroundPanel(null, BackgroundPanel.ACTUAL, 1.0f, 0.5f);
      middleTripsTab.setBorder(insideBorders);
      middleTripsTab.setLayout(new MigLayout(
         "insets 0",
         "15[]5[]5[]5[]5[]5[]15",
         ""));

      // *****************************************CREATE FOURTH (VIEW AND EDIT) PANEL IN TAB
      BackgroundPanel bottomTripsTab = new BackgroundPanel(null, BackgroundPanel.ACTUAL, 1.0f, 0.5f);
      bottomTripsTab.setBorder(insideBorders);
      bottomTripsTab.setLayout(new MigLayout("wrap 5"));
      Dimension bottomTrips = new Dimension(width, 250);
      //bottomFundraisersTab.setPreferredSize(bottomFundraiser);
      GradientPaint paintBottomTrips = new GradientPaint(0, 150, Color.LIGHT_GRAY, 100, 50, Color.DARK_GRAY);
      bottomTripsTab.setPaint(paintBottomTrips);


      // *****************************************CREATE AND ADD COMPONENTS TO NAV
      JLabel space0Label = new JLabel("");
      navPanel.add(space0Label, "");

      JButton previousButton = new JButton("Previous");
      navPanel.add(previousButton, "");

      possibleTrips = DBconnection.getTrips();
      formattedTrips = ArraySorter.sortArray(possibleTrips);
      DBconnection.closeConnection();
      tripsList = new JComboBox(formattedTrips.toArray());
      tripsList.setSelectedIndex(0);
      tripsList.setForeground(Color.BLACK);
      tripsList.setBackground(Color.WHITE);
      navPanel.add(tripsList, "width 250!, height 20!");

      JButton nextButton = new JButton("Next");
      navPanel.add(nextButton, "");

      JLabel space3Label = new JLabel("");
      navPanel.add(space3Label, "");

      searchTF = new JTextField("", 10);
      searchTF.setCaretColor(Color.WHITE);
      navPanel.add(searchTF, "height 20!, wrap");
      
      currentRB = new JRadioButton("Current Trips");
      currentRB.setSelected(true);
      
      pastRB = new JRadioButton("Past Trips");
      
      ButtonGroup group = new ButtonGroup();
      group.add(currentRB);
      group.add(pastRB);
      navPanel.add(currentRB, "cell 2 1, split 2"); 
      navPanel.add(pastRB, "");

      // *****************************************CREATE AND ADD TABLE TO THE TOP OF TAB (table)
      tripsTable = new Trips.myTable();
      JTable dataTable = new JTable(tripsTable);
      JScrollPane scrollPane = new JScrollPane(dataTable);
      dataTable.setFillsViewportHeight(true);
      topTripsTab.add(scrollPane);

      // *****************************************CREATE AND ADD COMPONENTS TO THE MIDDLE OF TAB  (pictures)
      // CALL TO INITIALIZE PICTURES IN WITH UPDATE TABLE
      tripSelected = tripsList.getSelectedItem().toString();
      tripID = ArraySorter.idFinder(possibleTrips, tripSelected);
      photosList = DBconnection.getTripPhotos(tripID);

      leftScroll = new JLabel("");
      leftScroll.setIcon(new ImageIcon(leftArrow));

      photo1 = new JLabel("");
      photo1.setBorder(border);

      photo2 = new JLabel("");
      photo2.setBorder(border);

      photo3 = new JLabel("");
      photo3.setBorder(border);

      photo4 = new JLabel("");
      photo4.setBorder(border);

      photo5 = new JLabel("");
      photo5.setBorder(border);

      photo6 = new JLabel("");
      photo6.setBorder(border);

      rightScroll = new JLabel("");
      rightScroll.setIcon(new ImageIcon(rightArrow));

      middleTripsTab.add(leftScroll,
         "shrink, width ::70, height :150:150, dock west");
      middleTripsTab.add(photo1,
         "shrink, width 75:150:, height 75:150:");
      middleTripsTab.add(photo2,
         "shrink, width 75:150:, height 75:150:");
      middleTripsTab.add(photo3,
         "shrink, width 75:150:, height 75:150:");
      middleTripsTab.add(photo4,
         "shrink, width 75:150:, height 75:150:");
      middleTripsTab.add(photo5,
         "shrink, width 75:150:, height 75:150:");
      middleTripsTab.add(photo6,
         "shrink, width 75:150:, height 75:150:");
      middleTripsTab.add(rightScroll,
         "shrink, width ::70, height :150:150, dock east");
      middleTripsTab.revalidate();

      // CALL TO PUT PICTURES ON THE LABELS
      setPictures(photoStartPosition);

      // *****************************************CREATE AND ADD COMPONENTS TO THE BOTTOM OF TAB (info)
      // ROW 1
      JLabel nameLabel = new JLabel("Name: ");
      nameLabel.setForeground(EPovertyMain.font);
      bottomTripsTab.add(nameLabel, "");

      tripNameCardPanel = new JPanel(new CardLayout());
      tripName = new JLabel("");
      tripNameTF = new JTextField();
      tripNameCardPanel.add(tripName, "view");
      tripNameCardPanel.add(tripNameTF, "edit");
      bottomTripsTab.add(tripNameCardPanel, "width 200!, height 25!");

      JLabel cutoffLabel = new JLabel("Cutoff Date: ");
      cutoffLabel.setForeground(EPovertyMain.font);
      bottomTripsTab.add(cutoffLabel, "");

      cutoffCardPanel = new JPanel(new CardLayout());
      cutoffDate = new JLabel("");
      cutoffDateTF = new JTextField(10);
      cutoffDateTF.setEditable(false);
      cutoffBTN = new JButton("PICK DATE");
      JPanel cutoffEditPanel = new JPanel(new MigLayout("insets 0"));
      cutoffEditPanel.add(cutoffDateTF, "height 25!");
      cutoffEditPanel.add(cutoffBTN, "height 23!");
      cutoffCardPanel.add(cutoffDate, "view");
      cutoffCardPanel.add(cutoffEditPanel, "edit");
      bottomTripsTab.add(cutoffCardPanel, "width 400!, height 25!, wrap");

      // ROW 2
      JLabel departLabel = new JLabel("Depart Date: ");
      departLabel.setForeground(EPovertyMain.font);
      bottomTripsTab.add(departLabel, "cell 2 2");

      departCardPanel = new JPanel(new CardLayout());
      departDate = new JLabel("");
      departDateTF = new JTextField(10);
      departDateTF.setEditable(false);
      departBTN = new JButton("PICK DATE");
      JPanel departEditPanel = new JPanel(new MigLayout("insets 0"));
      departEditPanel.add(departDateTF, "height 25!");
      departEditPanel.add(departBTN, "height 23!");
      departCardPanel.add(departDate, "view");
      departCardPanel.add(departEditPanel, "edit");
      bottomTripsTab.add(departCardPanel, "cell 3 2, width 400!, height 25!, wrap");

      // ROW 3
      JLabel returnLabel = new JLabel("Return Date: ");
      returnLabel.setForeground(EPovertyMain.font);
      bottomTripsTab.add(returnLabel, "cell 2 3");

      returnCardPanel = new JPanel(new CardLayout());
      returnDate = new JLabel("");
      returnDateTF = new JTextField(10);
      returnDateTF.setEditable(false);
      returnBTN = new JButton("PICK DATE");
      JPanel returnEditPanel = new JPanel(new MigLayout("insets 0"));
      returnEditPanel.add(returnDateTF, "height 25!");
      returnEditPanel.add(returnBTN, "height 23!");
      returnCardPanel.add(returnDate, "view");
      returnCardPanel.add(returnEditPanel, "edit");
      bottomTripsTab.add(returnCardPanel, "cell 3 3, width 400!, height 25!, wrap");

      // ROW 4
      JLabel costLabel = new JLabel("Cost: ");
      costLabel.setForeground(Color.DARK_GRAY);
      bottomTripsTab.add(costLabel, "");

      costCardPanel = new JPanel(new CardLayout());
      cost = new JLabel("");
      costTF = new JTextField();
      costCardPanel.add(cost, "view");
      costCardPanel.add(costTF, "edit");
      bottomTripsTab.add(costCardPanel, "width 200!, height 25!");

      JLabel descriptionLabel = new JLabel("Description: ");
      descriptionLabel.setForeground(EPovertyMain.font);
      bottomTripsTab.add(descriptionLabel, "");


      descriptionTA = new JTextArea(4, 30);
      descriptionTA.setEditable(false);
      JScrollPane descriptionSroll = new JScrollPane(descriptionTA); 
      descriptionSroll.getVerticalScrollBar().setPreferredSize (new Dimension(0,0));
      bottomTripsTab.add(descriptionSroll, "span 2 2, wrap, width 450!");

      // ROW 5
      JLabel defaultRaiseLabel = new JLabel("Default Raise Goal: ");
      defaultRaiseLabel.setForeground(Color.DARK_GRAY);
      bottomTripsTab.add(defaultRaiseLabel, "");

      defaultRaiseCardPanel = new JPanel(new CardLayout());
      defaultRaiseGoal = new JLabel("");
      defaultRaiseGoalTF = new JTextField();
      defaultRaiseCardPanel.add(defaultRaiseGoal, "view");
      defaultRaiseCardPanel.add(defaultRaiseGoalTF, "edit");
      bottomTripsTab.add(defaultRaiseCardPanel, "width 200!, height 25!, wrap");

      // ROW 5
      editBTN = new JButton("EDIT");
      bottomTripsTab.add(editBTN, "");
      editBTN.setOpaque(true);

      // CALL UPDATES TO INITIALIZE THE TABLE AND CONTACT INFO 
      tripSelected = tripsList.getSelectedItem().toString();
      tripID = ArraySorter.idFinder(possibleTrips, tripSelected);
      updateContactInfo(tripID);
      updateTable(tripID);

      // ADD TOP AND BOTTOM TO THE MAIN AND PUT THEM INTO A TAB
      mainPanel.add(navPanel,
         "growx, height 50:50:50");
      mainPanel.add(topTripsTab,
         "grow");
      mainPanel.add(middleTripsTab,
         "growx, height 150:150:150");
      mainPanel.add(bottomTripsTab,
         "grow, height 225::");

      mainPanel.revalidate();

      tabs.add(
         "", mainPanel);
      
           /**
       * Action listener for the previous button
       */
      previousButton.addActionListener(
         new ActionListener()
         {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                if (edit){
                    editBTN.doClick();
                }
                
               int selectedIndex = tripsList.getSelectedIndex();

               if (selectedIndex > 0)
               {
                  selectedIndex--;
               }
               tripsList.setSelectedIndex(selectedIndex);
            }
         });

      /**
       * Action listener for the next button
       */
      nextButton.addActionListener(
         new ActionListener()
         {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                if (edit){
                    editBTN.doClick();
                }
                
               int selectedIndex = tripsList.getSelectedIndex();
               int selectedMax = tripsList.getItemCount();

               if (selectedIndex < (selectedMax - 1))
               {
                  selectedIndex++;
               }
               tripsList.setSelectedIndex(selectedIndex);
            }
         });

      // ********************************************LISTENER FOR THE CURRENT RADIO BUTTON
      currentRB.addActionListener(
        new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                // Change drop down to list current trips (depart date has not passed)
                try 
                {
                    possibleTrips = DBconnection.getTrips();
                    formattedTrips = ArraySorter.sortArray(possibleTrips);
                    updateTripsList();
                    updateContactInfo(tripID);
                    updateTable(tripID);
                    editBTN.setEnabled(true);
                    editBTN.setText("Edit");
                } catch (SQLException ex) {
                    Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ParseException ex) {
                    Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                }  
            }
        });
      
      // ********************************************LISTENER FOR THE PAST RADIO BUTTON
      pastRB.addActionListener(
        new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                // Change drop down to list past trips (depart date has passed). Also, make the edit button un-clickable
                try 
                {
                    possibleTrips = DBconnection.getPastTrips();
                    formattedTrips = ArraySorter.sortArray(possibleTrips);
                    updateTripsList();
                    updateContactInfo(tripID);
                    updateTable(tripID);

                    if (DBconnection.isTripArchivable(tripID)) 
                    {
                        editBTN.setEnabled(true);
                    } else 
                    {
                        editBTN.setEnabled(false);
                    }
                    editBTN.setText("Archive");
                
                } catch (SQLException ex) {
                    Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ParseException ex) {
                    Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                }  
            }
        });
      
      //*********************************************ACTION LISTENER FOR EDIT BUTTON
      editBTN.addActionListener(
         new ActionListener()
         {
            @Override
            public void actionPerformed(ActionEvent e)
            {                
                String name;
                /*
                 * If we are looking at past trips (have already departed)
                */
                if (pastRB.isSelected())
                {
                    JLabel warning;            

                    UIManager.put("OptionPane.okButtonText", "CONTINUE");
                    final JPanel panel = new JPanel(new MigLayout("wrap 1"));

                    fundraisers = new Trips.myTable();
                    JTable dataTable = new JTable(fundraisers);
                    JScrollPane scrollPane = new JScrollPane(dataTable);
                    dataTable.setFillsViewportHeight(true);
                    panel.add(scrollPane, "");

                    try 
                    {
                        // FILL THE TABLE WITH THE CORRECT NAMES
                        fundraisers = DBconnection.getFundraisersByTrip(fundraisers, tripID);
                    } catch (SQLException ex) {
                        Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    fundraisers.fireTableDataChanged();

                    warning = new JLabel("<html>"
                            + "All fundraisers listed above will have their target goal, "
                            + "<br>current raised amount, and expedition reset."
                            + "<br>Make sure you want to continue. ");

                    panel.add(warning);

                    int result = JOptionPane.showConfirmDialog(null, panel, "Change Distribution",
                            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

                    // *****************************************IF 'OK' IS HIT VERYIFY.  OTHERWISE CANCEL
                    if (result == JOptionPane.OK_OPTION)
                    {
                        // Calls to move fundraiser and trip into expeditionHistory and reset the fundraisers 'stats'
                        try 
                        {
                            DBconnection.getFundraisersToReset(tripID);
                        } catch (SQLException ex) {
                            Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (ClassNotFoundException ex) {
                            Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }

                }
                /*
                 * Otherwise button is an edit button (we are viewing trips that have NOT left
                 */
                else
                {
                    if (!edit)
                    {
                        name = "edit";
                        edit = true;
                        editBTN.setText("Done");
                    }
                    else
                    {
                        name = "view";
                        edit = false;
                        editBTN.setText("Edit");

                        // Update
                        try
                        {
                            // CALL TO UPDATE THE DATABASE
                            updateDatabase(tripID);
                        }
                        catch (IOException ex)
                        {
                            Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        catch (NoSuchAlgorithmException ex)
                        {
                            Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        catch (SQLException ex)
                        {
                            Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        catch (ClassNotFoundException ex)
                        {
                            Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        catch (ParseException ex)
                        {
                            Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                

                    CardLayout cl = (CardLayout) (tripNameCardPanel.getLayout());
                    cl.show(tripNameCardPanel, name);

                    cl = (CardLayout) (cutoffCardPanel.getLayout());
                    cl.show(cutoffCardPanel, name);

                    cl = (CardLayout) (departCardPanel.getLayout());
                    cl.show(departCardPanel, name);

                    cl = (CardLayout) (returnCardPanel.getLayout());
                    cl.show(returnCardPanel, name);

                    cl = (CardLayout) (costCardPanel.getLayout());
                    cl.show(costCardPanel, name);

                    cl = (CardLayout) (defaultRaiseCardPanel.getLayout());
                    cl.show(defaultRaiseCardPanel, name);

                    if (edit)
                    {
                        descriptionTA.setEditable(true);
                    }
                    else
                    {
                        descriptionTA.setEditable(false);
                    }
                }
               
               try
               {
                  // UPDATE THE INFORMATION DISPLAYED TO THE PERSON SELECTED
                  getInfoForUpdate(tripID);
               }
               catch (SQLException ex)
               {
                  Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
               }
               catch (ClassNotFoundException ex)
               {
                  Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
               }
            }
         });

        // LISTENERS FOR DATE PICKER BUTTONS
       departBTN.addActionListener(new ActionListener() 
       {

           @Override
           public void actionPerformed(ActionEvent ae) 
           {               
               // Check if depart date is before return date
               String datePicked = new DatePicker(f).setPickedDate();
               DateFormat formatter;
               Date dateReturn, dateDepart;
               formatter = new SimpleDateFormat("yyyy-MM-dd");
               
              
              if (!returnDateTF.getText().isEmpty())
              {
                    try 
                    {
                        dateReturn = (Date) formatter.parse(returnDateTF.getText());
                        dateDepart = (Date) formatter.parse(datePicked);
                        if (dateReturn.after(dateDepart)) 
                        {
                            departDateTF.setText(datePicked);
                        }
                        else
                        {
                            departDateTF.setText("");
                            new Warnings("Depart date can not be after Cutoff date!sssss");
                        }
                    } catch (ParseException ex) {
                        Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                    }
                  
              }
              else
              {
                  departDateTF.setText(datePicked);
              }

               try 
               {
                   if (!departDateTF.getText().isEmpty())
                   {    
                       dateDepart = (Date) formatter.parse(departDateTF.getText());
                       Calendar cal = Calendar.getInstance();
                       cal.setTime(dateDepart);
                       cal.add(Calendar.MONTH, -6);
                       dateDepart = cal.getTime();
                       cutoffDateTF.setText(formatter.format(dateDepart));
                   }
               } catch (ParseException ex) {
                   Logger.getLogger(EPovertyMain.class.getName()).log(Level.SEVERE, null, ex);
               }
           }
       });
       returnBTN.addActionListener(new ActionListener() 
       {

           @Override
           public void actionPerformed(ActionEvent ae) 
           {
               String datePicked = new DatePicker(f).setPickedDate();
               DateFormat formatter;
               Date dateReturn, dateDepart;
               formatter = new SimpleDateFormat("yyyy-MM-dd");
               try 
               {
                   if (!departDateTF.getText().isEmpty())
                   {
                       dateReturn = (Date) formatter.parse(datePicked);
                       dateDepart = (Date) formatter.parse(departDateTF.getText());

                       if (dateReturn.after(dateDepart)) 
                       {
                           returnDateTF.setText(datePicked);
                       } 
                       else 
                       {
                           returnDateTF.setText("");
                           new Warnings("Return date can not be before the depart date!");
                       }
                   }
                   else
                   {
                       returnDateTF.setText(datePicked);
                   }

               } catch (ParseException ex) {
                   Logger.getLogger(EPovertyMain.class.getName()).log(Level.SEVERE, null, ex);
               }
           }
       });
       cutoffBTN.addActionListener(new ActionListener() 
       {

           @Override
           public void actionPerformed(ActionEvent ae) 
           {
               cutoffDateTF.setText(new DatePicker(f).setPickedDate());
           }
       });

      // *****************************************LISTENER FOR THE LEFT SCROLL JLabel
      leftScroll.addMouseListener(
         new MouseListener()
         {
            @Override
            public void mouseClicked(MouseEvent e)
            {
               if (photoStartPosition + 6 < photosList.size())
               {
                  photoStartPosition++;
                  setPictures(photoStartPosition);
               }
            }

            @Override
            public void mousePressed(MouseEvent e)
            {
            }

            @Override
            public void mouseReleased(MouseEvent e)
            {
            }

            @Override
            public void mouseEntered(MouseEvent e)
            {
            }

            @Override
            public void mouseExited(MouseEvent e)
            {
            }
         });

      // *****************************************LISTENER FOR THE RIGHT SCROLL JLabel
      rightScroll.addMouseListener(
         new MouseListener()
         {
            @Override
            public void mouseClicked(MouseEvent e)
            {
               if (photoStartPosition > 0)
               {
                  photoStartPosition--;
                  setPictures(photoStartPosition);
               }
            }

            @Override
            public void mousePressed(MouseEvent e)
            {
            }

            @Override
            public void mouseReleased(MouseEvent e)
            {
            }

            @Override
            public void mouseEntered(MouseEvent e)
            {
            }

            @Override
            public void mouseExited(MouseEvent e)
            {
            }
         });

      searchTF.addKeyListener(
         new KeyListener()
         {
            @Override
            public void keyTyped(KeyEvent e)
            {
            }

            @Override
            public void keyPressed(KeyEvent e)
            {
            }

            @Override
            public void keyReleased(KeyEvent e)
            {
               JTextField textField = (JTextField) e.getSource();
               String text = textField.getText();
               textField.setText(text);
               try
               {
                  updateComboBox();
               }
               catch (SQLException ex)
               {
                  Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
               }
               catch (ClassNotFoundException ex)
               {
                  Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
               }
            }
         });

      // ITEM LISTENER FOR COMBO BOX
      tripsList.addItemListener(
         new ItemListener()
         {
            String tripSelected;

            @Override
            public void itemStateChanged(ItemEvent e)
            {
               // WHEN SOMEONE IS SELECTED FROM THE COMBOBOX GET THEIR INFORMATION
               if (e.getStateChange() == ItemEvent.DESELECTED)
               {
               }
               if (e.getStateChange() == ItemEvent.SELECTED)
               {
                   String name;
                   if (edit)
                   {
                       name = "view";
                       edit = false;
                       CardLayout cl = (CardLayout) (tripNameCardPanel.getLayout());
                       cl.show(tripNameCardPanel, name);

                       cl = (CardLayout) (cutoffCardPanel.getLayout());
                       cl.show(cutoffCardPanel, name);

                       cl = (CardLayout) (departCardPanel.getLayout());
                       cl.show(departCardPanel, name);

                       cl = (CardLayout) (returnCardPanel.getLayout());
                       cl.show(returnCardPanel, name);

                       cl = (CardLayout) (costCardPanel.getLayout());
                       cl.show(costCardPanel, name);

                       cl = (CardLayout) (defaultRaiseCardPanel.getLayout());
                       cl.show(defaultRaiseCardPanel, name);
                   }       
                   
                  tripSelected = tripsList.getSelectedItem().toString();
                  tripID = ArraySorter.idFinder(possibleTrips, tripSelected);
                  
                  // Check if we are looking at past trips (have departed), or new trips (have not departed)
                  if (pastRB.isSelected())
                  {
                                            
                      // See if button should be enabled
                      // Check if trip has returned (returnDate has passed) and trip is NOT already in history
                      try 
                      {
                          if (DBconnection.isTripArchivable(tripID)) 
                          {
                              editBTN.setEnabled(true);
                          }
                          else
                          {
                              editBTN.setEnabled(false);
                          }
                      } catch (SQLException ex) {
                          Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                      } catch (ClassNotFoundException ex) {
                          Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                      }
                  }
                  // UPDATE CONTACT INFO AND TABLE
                  try
                  {
                      updateContactInfo(tripID);
                      updateTable(tripID);
                      photosList = DBconnection.getTripPhotos(tripID);

                     // RESET ALL PHOTOS TO DEFAULT BEFORE GETTING NEW PICTURES
                     // IN CASE NEW TRIP HAS LESS THAN 6 PICTURES
                     photo1.setIcon(new ImageIcon(defaultImage));
                     photo2.setIcon(new ImageIcon(defaultImage));
                     photo3.setIcon(new ImageIcon(defaultImage));
                     photo4.setIcon(new ImageIcon(defaultImage));
                     photo5.setIcon(new ImageIcon(defaultImage));
                     photo6.setIcon(new ImageIcon(defaultImage));

                     // RESET STARTING POSITION TO 0 AND SET UP THE PICTURES
                     photoStartPosition = 0;
                     setPictures(photoStartPosition); 
                     
                   } catch (IOException ex) {
                       Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                   } catch (ClassNotFoundException ex) {
                       Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                   } catch (SQLException ex) {
                       Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                   } catch (ParseException ex) {
                       Logger.getLogger(Trips.class.getName()).log(Level.SEVERE, null, ex);
                   }
               }
            }
         });
      // END OF ITEM LISTENER FOR COMBO BOX      
   }

   // ********************************************METHOD TO UPDATE CONTACT INFO BASED ON PERSON SELECTED
   private void updateContactInfo(int tripID) throws SQLException, ClassNotFoundException, IOException
   {
      // GET ALL INFO FOR THE TRIP AND DISPLAY THE RESULTS BASED ON TRIP ID
      ArrayList<Object> tripData = DBconnection.getTrips(tripID);
      String[] tripInfo = tripData.toString().split(",");
      
      tripName.setText(tripInfo[1]);
      descriptionTA.setText(tripInfo[2]);
      cost.setText(tripInfo[3]);
      defaultRaiseGoal.setText(tripInfo[4]);
      departDate.setText(tripInfo[5]);
      returnDate.setText(tripInfo[6]);
      cutoffDate.setText(tripInfo[7].substring(0, tripInfo[7].length() -2));
   }

   // ********************************************METHOD TO UPDATE CONTACT INFO BASED ON PERSON SELECTED
   private void getInfoForUpdate(int tripID) throws SQLException, ClassNotFoundException
   {
      // GET ALL INFO FOR THE TRIP AND DISPLAY THE RESULTS BASED ON TRIP ID
      ArrayList<Object> tripData = DBconnection.getTrips(tripID);
      String[] tripInfo = tripData.toString().split(",");
      
      tripNameTF.setText(tripInfo[1].substring(1, tripInfo[1].length()));
      descriptionTA.setText(tripInfo[2].substring(1, tripInfo[2].length()));
      costTF.setText(tripInfo[3].substring(1, tripInfo[3].length()));
      defaultRaiseGoalTF.setText(tripInfo[4].substring(1, tripInfo[4].length()));
      departDateTF.setText(tripInfo[5].substring(1, tripInfo[5].length()));
      returnDateTF.setText(tripInfo[6].substring(1, tripInfo[6].length()));
      cutoffDateTF.setText(tripInfo[7].substring(1, tripInfo[7].length() -2));
   }

   // ********************************************METHOD TO UPDATE THE TABLE
   private void updateTable(int tripId) throws SQLException, ClassNotFoundException, ParseException
   {
      // UPDATE TABLE AND THEN LET THE TABLE KNOW THE DATA HAS CHANGED
      tripsTable = DBconnection.getFundraisersInfoByTrip(tripsTable, tripId);
      tripsTable.fireTableDataChanged();
   }

   // ********************************************METHOD TO UPDATE DATABASE
   private void updateDatabase(int tripId) throws SQLException, ClassNotFoundException, NoSuchAlgorithmException, UnsupportedEncodingException, IOException, ParseException
   {
      DBconnection.updateTrip(tripId+"", tripNameTF.getText(), descriptionTA.getText(), costTF.getText(), defaultRaiseGoalTF.getText(),
              departDateTF.getText(), returnDateTF.getText(), cutoffDateTF.getText());
      
      
      // Gets the currently selected trip, then updates the trip info, and the drop down box, and selects the current trip again
       int selected = tripsList.getSelectedIndex();
       possibleTrips = DBconnection.getTrips();
       formattedTrips = ArraySorter.sortArray(possibleTrips);
       updateTripsList();
       updateContactInfo(tripID);
       updateTable(tripID);
       tripsList.setSelectedIndex(selected);
   }

   // **************************************UPDATES THE COMBO BOX TO REFLECT ALL FUNDRAISERS MATCHING SEARCH CRITERIA
   private void updateComboBox() throws SQLException, ClassNotFoundException
   {
      Object[] fundraiserNames = formattedTrips.toArray();

      Pattern p = Pattern.compile(searchTF.getText(), Pattern.CASE_INSENSITIVE);
      tripsList.removeAllItems();
      for (int i = 0; i < fundraiserNames.length; i++)
      {
         String elem = fundraiserNames[i].toString();
         Matcher m = p.matcher(elem);
         if (m.find())
         {
            tripsList.addItem(fundraiserNames[i]);
         }
      }
   }

   // ********************************************METHOD THAT ALLOWS OTHER CLASSES TO UPDATE THE FUNDRAISER LIST
   public static void updateTripsList() throws SQLException, ClassNotFoundException
   {
      Object[] arrayOfNames = formattedTrips.toArray();
      tripsList.removeAllItems();
      for (int x = 0; x < formattedTrips.size(); x++)
      {
         tripsList.addItem(arrayOfNames[x]);
      }
   }

   //Prevents cells from being edited in table by overriding isCellEditable.
   public class myTable extends DefaultTableModel
   {
      @Override
      public boolean isCellEditable(int row, int col)
      {
         return false;
      }
   }

   // ********************************************USED TO SET AND RESET THE PICTURES DISPLAYED
   public void setPictures(int startingPosition)
   {
      // Find out how many pictures are in the ArrayList
      int numberOfPhotos = photosList.size();

      // MAKE SURE THERE IS AT LEAST ONE PHOTO
      if (numberOfPhotos > 0)
      {
         // CHECK TO MAKE SURE ONLY 6 PHOTOS ARE UPDATED, AND AS LONG AS THERE IS 6 OR MORE PHOTOS EVERY LABEL HAS A PHOTO
         for (int x = 0; x < 6 && (x + startingPosition) < numberOfPhotos; x++)
         {
            switch (x)
            {
               case 0:
                  photo1.setIcon(new ImageIcon(photosList.get(x + startingPosition)));
                  break;
               case 1:
                  photo2.setIcon(new ImageIcon(photosList.get(x + startingPosition)));
                  break;
               case 2:
                  photo3.setIcon(new ImageIcon(photosList.get(x + startingPosition)));
                  break;
               case 3:
                  photo4.setIcon(new ImageIcon(photosList.get(x + startingPosition)));
                  break;
               case 4:
                  photo5.setIcon(new ImageIcon(photosList.get(x + startingPosition)));
                  break;
               case 5:
                  photo6.setIcon(new ImageIcon(photosList.get(x + startingPosition)));
                  break;
               default:
                  break;
            }
         }
      }
      else
      {
          photo1.setIcon(new ImageIcon(defaultImage));
          photo2.setIcon(new ImageIcon(defaultImage));
          photo3.setIcon(new ImageIcon(defaultImage));
          photo4.setIcon(new ImageIcon(defaultImage));
          photo5.setIcon(new ImageIcon(defaultImage));
          photo6.setIcon(new ImageIcon(defaultImage));
      }
   }
}
